package org.example;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class JsonLibTest {
    public static void main(String[] args) {

        //map转为json字符串
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("name", "veeja");
        jsonObject.put("age", 18);
        jsonObject.put("sex", "male");
        jsonObject.element("1234", "5678");
        System.out.println(jsonObject.toString());

        //对象转为json字符串
        Person p = new Person("veeja", 18, "male");
        JSONObject map = JSONObject.fromObject(p);
        System.out.println(map.toString());

        //JSONArray本身是一个List
        Person p1 = new Person("aaa", 21, "male");
        Person p2 = new Person("bbb", 18, "female");
        JSONArray jsonArray = new JSONArray();
        jsonArray.add(p1);
        jsonArray.add(p2);
        System.out.println(jsonArray.toString());

        //如果已经有了一个List，我们需要把List转换成JSONArray
        p1 = new Person("ccc", 21, "male");
        p2 = new Person("ddd", 18, "female");
        List<Person> list = new ArrayList<>();
        list.add(p1);
        list.add(p2);

        jsonArray = JSONArray.fromObject(list);
        System.out.println(jsonArray.toString());


    }
}